<?php

defined('SYSPATH') or die('No direct script access.');

class Controller_Projects extends Controller_Template {

    public $template = 'main';
    private $project_id;
    
    public function before() {
        parent::before();
        if (!Auth::instance()->logged_in() AND Request::current()->uri() !== 'login') {
            $this->request->redirect('/login');
        }
        $this->username = Auth::instance()->get_user()->username;
        $model = ORM::factory('project')->where("domain", "=", $this->username)->find();
        $this->project_id = $model->project_id;
    }

    public function action_index() {
        $paramsauth = Array();
        $count = 0;
        $id_user = Auth::instance()->get_user()->id;
        $model = ORM::factory('rookeeaccount')->find();
        $paramsauth["login"] = $model->username; // Логин
        $paramsauth["password"] = $model->password; // Пароль
        $api = new Model_Api($paramsauth);
        $project_id = $this->request->param('id');
        $hz = array();
        #Если указан id проекта то показываем информацию по его запросам и позициям
        if ($project_id) {
            $model_project = ORM::factory('project')->where("user_id", "=", $id_user)->find();
            if ($project_id != $model_project->project_id and $id_user != 1) {
                $this->request->redirect('member');
            }

            $interval = Arr::get($_POST, 'list', 'За месяц');
            switch ($interval) {
                case 'За месяц':
                    $interval = strtotime('-1 month');
                    break;
                case 'За квартал':
                    $interval = strtotime('-3 month');
                    break;
                case 'За пол года':
                    $interval = strtotime('-6 month');
                    break;
                case 'За год':
                    $interval = strtotime('-1 year');
                    break;
                default:
                    $interval = strtotime('-1 month');
                    break;
            }
            $queries = $api->getQueries($project_id);
            if (!empty($queries)) {
                foreach ($queries as $key => $query) {
                    Model::factory('Main')->update_queries($query['id'], $project_id, $query['title'], $query['target']);
                    $count++;
                    $position = $api->getPositions($query['id'], date('Y-m-d', date(strtotime('-1 month'))), date('Y-m-d'));
                    foreach ($position as $k => $pos) {
                        Model::factory('Main')->update_positions($query['id'], $pos->Date, $pos->PositionYandex, $pos->PositionGoogle);
                    }
                    $positions = Model::factory('Main')->get_positions($query['id'], $interval);
                    foreach ($positions as $k => $pos) {
                        $date = date("d M", $pos->date);
                        $hz[$k]['date'] = $date;
                        if (!isset($hz[$k]['yandex']) and !isset($hz[$k]['google'])) {
                            $hz[$k]['yandex'] = 0;
                            $hz[$k]['google'] = 0;
                        }
                        $hz[$k]['yandex'] = $hz[$k]['yandex'] + $pos->yandex;
                        $hz[$k]['google'] = $hz[$k]['google'] + $pos->google;
                        $arr[$key][$k]['yandex'] = $pos->yandex;
                        $arr[$key][$k]['google'] = $pos->google;
                    }
                    $queries[$key]['pos']['yandex'] = $positions[count($positions) - 1]->yandex;
                    $queries[$key]['pos']['google'] = $positions[count($positions) - 1]->google;
                }
                foreach ($hz as $k => $h) {
                    $hz[$k]['yandex'] = floor($hz[$k]['yandex'] / $count);
                    $hz[$k]['google'] = floor($hz[$k]['google'] / $count);
                }
                $project = $api->getProject($project_id);
                $data['project'] = $project->Domain;
                $data['queries'] = $queries;
                $data['hz'] = $hz;
                $data['arr'] = $arr;
                $content = View::factory('queries', $data);
            } else {
                $content = "";
            }
            $this->template->project_id = $this->project_id;
            $this->template->title = "Проект " . $project->Domain;
            $this->template->content = $content;
            #Если не указан id проекта и юзер админ то показываем все проекты
        } elseif (Auth::instance()->logged_in('admin')) {
            $projects = $api->getProjects();
            if (!empty($projects)) {
                foreach ($projects as $key => $project) {
                    $region_id = $api->getProjectRegion($project['id']);
                    $regions[] = ORM::factory('region')->where("reg_id", "=", $region_id)->find()->name;
                    Model::factory('main')->update_projects($project['id'], $project['domain'], $region_id);
                }
                $data['projects'] = $projects;
                $data['regions'] = $regions;
                $content = View::factory('index', $data);
            } else {
                $content = "";
            }
            $this->template = View::factory('admin_template');
            $this->template->title = "Проекты";
            $this->template->content = $content;
        } else {
            $this->template->content = "Вы не имеете доступ к этой странице";
        }
    }

}
